package com.sky.utils;

import com.alibaba.fastjson.JSONObject;
import com.sky.properties.BaiduProperties;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.management.MBeanAttributeInfo;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Component
public class BaiduUtil {
    //可以到配置文件设置为自己百度应用的ak
    @Autowired
    private BaiduProperties baiduProperties;
    //骑行路线规划
    private static String url1 = "https://api.map.baidu.com/directionlite/v1/riding";
    //获取地址对应经纬度
    private static String url2 = "https://api.map.baidu.com/geocoding/v3/";

    /**
     * 获得两个地址之间的距离
     * @param origin 起始地
     * @param destination 目的地
     * @return 两地之间规划距离
     */
    public  Long getDistance(String origin, String destination) {
        Map<String, String> map = new HashMap<>();
        map.put("origin", getLongitudeAndLatitude(origin));
        map.put("destination", getLongitudeAndLatitude(destination));
        map.put("riding_type", "1");
        map.put("ak", baiduProperties.getAk());
        String data = HttpClientUtil.doGet(url1, map);
       log.info("路径规划信息：{}",data);
        return  JSONObject
                .parseObject(data)
                .getJSONObject("result")
                .getJSONArray("routes")
                .stream()
                .map(obj->JSONObject.parseObject(obj.toString()))
                .min((o1, o2) -> Integer.compare(o1.getInteger("distance"),o2.getInteger("distance")))
                .get()
                .getLong("distance");

    }
    //获取一个地址的经纬度
    public  String getLongitudeAndLatitude(String address) {
        Map<String, String> map = new HashMap<>();
        map.put("address", address);
        map.put("output", "json");
        map.put("ak", baiduProperties.getAk());
        String data = HttpClientUtil.doGet(url2, map);
        /*
        {
            "status": 0,
            "result": {
                "location": {
                    "lng": 121.61932912757078,
                    "lat": 31.04135479189867
                },
                "precise": 1,
                "confidence": 80,
                "comprehension": 100,
                "level": "门址"
            }
        }
         */
        JSONObject jsonObject = JSONObject.parseObject(data);
        JSONObject result = jsonObject.getJSONObject("result");
        JSONObject location = result.getJSONObject("location");
        //39.936404,116.452562
        //121.619331,31.041355
        String lanAndLnt = String.format("%.6f", location.getFloat("lat"))
                + "," +
                String.format("%.6f", location.getFloat("lng"));
        log.info(address+"的纬度经度为{}",lanAndLnt);
        return lanAndLnt;

    }
}
